/**
 * 行业 业务组件 树形结构(不支持筛选)
 * by zhanghaitao
 * create 2021-10-19
 */
import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { TreeSelect, Tooltip, Select } from 'antd';
import { FormItemLayout, NoLableLayout } from '../../form/formPub.js';
import { SelectC } from '../../../comps';
import _ from 'lodash';
@Form.create()
class IndustryC extends React.PureComponent {
  // props默认值
  static defaultProps = {
    title: '行业',
    placeholder: '请选择行业',
    helper: '',
    onChange: () => {},
    onRef: () => {}, // 本组件的引用
    width: '100%',
    maxTagCount: 0,
    rules: undefined, // 默认无校验规则
    multiple: true, // 默认支持多选
    formItemLayout: FormItemLayout, // 设置form表单布局默认值
    allowClear: true, // 默认可删除
    disabled: false, // 默认不禁用
    treeCheckable: false, // 默认不显示
    isTree: true, // 是否树形结构
    treeNode: 3, // 第几级树形结构
    isUnfold: true, // 是否展开树节点，默认展开
    labalWrap: false, //默认title不换行
  };

  constructor(props) {
    super(props);
    this.state = {
      treeExpandedKeys: [], // 记录树展开的节点（解决数据刷新时，树节点未默认展开问题）
      data: [], // 数据源
      tooltipInfo: '',
    };
  }

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
    // 初始化数据
    this.initSeletData();
    if (this.props.isTree) {
      if (this.props.initialValue != undefined && this.props.initialValue != null) {
        this.setTooltip(this.props.initialValue);
      }
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.isTree) {
      // 处理当重置时，清空tooltip
      let value = nextProps.form.getFieldValue(nextProps.dataIndex);
      this.setTooltip(value);
    }
    // 响应外部组件行业切换场景
    if (this.props.treeNode != nextProps.treeNode) {
      setTimeout(() => {
        this.treeDataChange();
      }, 500);
    }
  }

  // 初始化下拉数据
  initSeletData = () => {
    // 调用接口，获取产品下的组合数据
    this.props.dispatch({
      type: 'industryM/getIndustry',
      payload: {},
      callback: (data) => {
        if (data) {
          let keys = [];
          if (this.props.isTree) {
            // 找出所有父节点，并展开
            this.findParentKey(data, keys);
          }
          // 初始数据
          this.initData = data;
          this.setState(
            {
              treeExpandedKeys: keys,
            },
            () => this.treeDataChange(),
          );
        } else {
          this.setState({
            treeExpandedKeys: [],
          });
        }
      },
    });
  };
  // 展示树的层级结构
  treeDataChange = () => {
    const { isTree, treeNode } = this.props;
    let ary = [];
    if (isTree) {
      if (treeNode == 1) {
        ary = _.cloneDeep(this.initData);
        ary.map((i) => {
          delete i.children;
        });
      } else if (treeNode == 2) {
        ary = _.cloneDeep(this.initData);
        ary?.map((item) => {
          item.children?.map((i) => {
            delete i.children;
          });
        });
      } else {
        ary = this.initData;
      }
    } else {
      if (treeNode == 1) {
        ary = _.cloneDeep(this.initData);
      } else if (treeNode == 2) {
        this.initData?.forEach((item) => {
          ary.push(...item.children);
        });
      } else {
        this.initData?.forEach((item) => {
          item.children.forEach((i) => {
            ary.push(...i.children);
          });
        });
      }
      treeNode != 3 &&
        ary.map((i) => {
          delete i.children;
        });
    }
    this.setState({ data: ary });
  };

  // 遍历树形结构，找出所有非叶子节点
  findParentKey = (data, keys) => {
    if (data && data.length > 0) {
      data.forEach((item) => {
        if (item && item.children && item.children.length > 0) {
          keys.push(item.value);
          this.findParentKey(item.children, keys);
        }
      });
    }
  };

  // 非初始化状态下更改下拉选项(供父组件调用)
  setSelect = (value) => {
    if (this.props.isTree) {
      const valueF = {};
      valueF[this.props.dataIndex] = value;
      this.props.form.setFieldsValue(valueF);
      // 响应变更事件
      this.onChange(value);
      this.setTooltip(value);
    } else {
      this.state.Industry.setSelect(value);
    }
  };

  // 树节点展开事件，解决数据刷新时，树节点未默认展开问题
  onTreeExpand = (expandedKeys) => {
    this.setState({
      treeExpandedKeys: expandedKeys,
    });
  };

  // 根据key值，遍历树节点
  findNode = (data, key, node) => {
    data.forEach((element) => {
      if (element.value == key) {
        node.push(element);
      }
      if (element.children) {
        this.findNode(element.children, key, node);
      }
    });
  };

  // 选中树节点变更事件
  onChange = (e) => {
    if (e == undefined || e.length == 0) {
      this.props.onChange(undefined);
      return;
    }
    let args = { key: e, info: undefined };
    let ds = this.state.data;
    let tooltipInfo = '';
    // 多选
    if (this.props.multiple) {
      let info = [];
      e.forEach((element, index) => {
        let temp = [];
        this.findNode(ds, element, temp);
        info.push(temp[0]);
        if (temp.length > 0) {
          tooltipInfo += temp[0].title;
        }
        // 最后一个元素之后不用换行
        if (index != e.length - 1) {
          tooltipInfo += '\r\n';
        }
      });
      args.info = info;
    } else {
      // 单选
      let temp = [];
      this.findNode(ds, e, temp);
      args.info = temp[0];
      if (temp.length > 0) {
        tooltipInfo += temp[0].title;
      }
    }
    this.props.onChange(args);
    this.setState({
      tooltipInfo: tooltipInfo == '' ? '' : <div style={{ whiteSpace: 'pre' }}>{tooltipInfo}</div>,
    });
  };

  // 响应非树形结构下拉变更事件
  onChange1 = (e) => {
    this.props.onChange(e);
  };

  // 模糊查询，匹配Name或code
  filterTreeNode = (inputValue, treeNode) => {
    let value = treeNode.props.value;
    let name = treeNode.props.title;
    return value.indexOf(inputValue) > -1 || name.indexOf(inputValue) > -1;
  };

  // 设置tooltip
  setTooltip = (e, propT = this.props) => {
    let ds = this.state.data;
    if (ds == undefined) return;
    let { multiple } = propT;
    let tooltipInfo = '';
    if (e != undefined && e != null) {
      if (Array.isArray(e) && multiple) {
        // 多选
        e.forEach((element, index) => {
          let nodeInfo = [];
          this.findNode(ds, element, nodeInfo);

          if (nodeInfo.length > 0) {
            tooltipInfo += nodeInfo[0].title;
          }
          // 最后一个元素之后不用换行
          if (index != e.length - 1) {
            tooltipInfo += '\r\n';
          }
        });
      } else {
        // 单选
        let nodeInfo = [];
        this.findNode(ds, e, nodeInfo);
        if (nodeInfo.length > 0) {
          tooltipInfo += nodeInfo[0].title;
        }
      }
    }
    this.setState({
      tooltipInfo: tooltipInfo == '' ? '' : <div style={{ whiteSpace: 'pre' }}>{tooltipInfo}</div>,
    });
  };
  render() {
    const {
      labalWrap,
      styleRow,
      form,
      title,
      dataIndex,
      initialValue,
      placeholder,
      helper,
      maxTagCount,
      width,
      multiple,
      rules,
      formItemLayout,
      allowClear,
      disabled,
      treeCheckable,
      isTree,
      treeNode,
      isUnfold,
    } = this.props;
    const { getFieldDecorator } = form;
    return isTree && treeNode != 1 ? (
      <Form.Item
        className={labalWrap ? 'labalWrap' : ''}
        labelCol={title ? formItemLayout.labelCol : NoLableLayout.labelCol}
        wrapperCol={title ? formItemLayout.wrapperCol : NoLableLayout.wrapperCol}
        label={
          title ? (
            helper ? (
              <span>
                {title}&nbsp;
                <Tooltip title={helper}>
                  <QuestionCircleOutlined />
                </Tooltip>
              </span>
            ) : (
              <span>{title}</span>
            )
          ) : undefined
        }
      >
        <Tooltip title={this.state.tooltipInfo}>
          <div>
            {getFieldDecorator(dataIndex, {
              initialValue,
              rules: !!rules ? rules : [],
            })(
              <TreeSelect
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                style={styleRow ? styleRow : { width: width }}
                maxTagCount={maxTagCount}
                placeholder={placeholder} // 占位符
                onChange={this.onChange} // 选中树节点时调用此函数
                treeData={this.state.data} // 数据源
                multiple={multiple} // 支持多选（当设置 treeCheckable 时自动变为 true）
                treeCheckable={treeCheckable} // 设置checkbox的显示或隐藏
                showCheckedStrategy={treeCheckable ? TreeSelect.SHOW_ALL : TreeSelect.SHOW_CHILD}
                allowClear={allowClear} // 显示清除按钮
                treeDefaultExpandAll={isUnfold} // 默认展开所有树节点（仅初始化时生效）
                // treeDefaultExpandedKeys={isUnfold?this.state.treeExpandedKeys:[]}
                // treeExpandedKeys={this.state.treeExpandedKeys}   // 设置树节点展开
                onTreeExpand={this.onTreeExpand} // 树节点展开调用事件
                dropdownMatchSelectWidth={true} // 下拉菜单和选择器同宽
                disabled={disabled}
                showSearch={true} // 支持模糊查询
                filterTreeNode={this.filterTreeNode}
              />,
            )}
          </div>
        </Tooltip>
      </Form.Item>
    ) : (
      <SelectC
        labalWrap={labalWrap}
        form={this.props.form}
        title={title}
        helper={helper}
        dataIndex={dataIndex}
        initialValue={initialValue}
        style={styleRow ? { width: width, ...styleRow } : { width: width }}
        maxTagCount={maxTagCount}
        placeholder={placeholder} // 占位符
        onChange={this.onChange1} // 选中时调用此函数
        dataSource={this.state.data} // 数据源
        isMultiple={multiple} // 支持多选
        allowClear={allowClear} // 显示清除按钮
        dropdownMatchSelectWidth={true} // 下拉菜单和选择器同宽
        disabled={disabled}
        showSearch={true} // 支持模糊查询
        onRef={(ref) => this.setState({ Industry: ref })}
      />
    );
  }
}

// props类型
IndustryC.propsTypes = {
  form: PropTypes.object, // form对象
  title: PropTypes.string, // 显示名称
  dataIndex: PropTypes.string, // Form识别的Item ID
  initialValue: PropTypes.oneOfType([
    // 初始默认值
    PropTypes.string, // 单选模式
    PropTypes.array, // 多选模式
  ]),
  rules: PropTypes.object, // 校验规则
  placeholder: PropTypes.string, // 占位符
  onChange: PropTypes.func, // 输入框内容变化时的回调
  helper: PropTypes.oneOfType([
    // 提示帮助信息
    PropTypes.string,
    PropTypes.element,
  ]),
  onRef: PropTypes.func, // 本组件的引用（可用来父组件调用内部方法）
  maxTagCount: PropTypes.number,
  multiple: PropTypes.bool, // 是否支持多选
  formItemLayout: PropTypes.object, // 设置表单布局
  allowClear: PropTypes.bool, // 设置是否可删除
  disabled: PropTypes.bool, // 是否禁用
  treeCheckable: PropTypes.bool, // 是否显示checkbox
  isTree: PropTypes.bool, // 是否树形结构
  treeNode: PropTypes.number, // 第几级树形结构
  isUnfold: PropTypes.bool, // 是否展开树节点
};

export default connect(({ industryM, loading }) => ({ industryM, loading }))(IndustryC);
